import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { objToQueryString } from "@/utils/object";
import { AppData } from "@/utils/app";

export const useShare = (
  path = "",
  hook?: (options: Page.ShareAppMessageOption) => void
) => {
  const shareOption: {
    title?: string;
    imageUrl?: string;
    data?: any;
    path?: string;
  } = { path };

  const getShareQuery = () => {
    /**
     * 分享时携带用户渠道、uid
     */
    const userData = AppData.userData;
    return objToQueryString(
      Object.assign(
        {
          utm_tid: userData?.tag_id || AppData.bundleData.tagId,
          share_uid: userData?.uid || "",
        },
        shareOption.data
      )
    );
  };

  onShareAppMessage(options => {
    hook?.(options);
    const query = getShareQuery();
    return {
      title: shareOption.title || "",
      imageUrl: shareOption.imageUrl,
      path: query ? `${shareOption.path}?${query}` : shareOption.path,
    };
  });

  onShareTimeline(() => {
    return {
      title: shareOption.title || "",
      imageUrl: shareOption.imageUrl,
      query: getShareQuery(),
    };
  });
  return { shareOption, onShareAppMessage, onShareTimeline };
};
